package heima_bixiangdong.test;

import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Getter
@Setter
class TrainTicket2 {
    private String ticketName;
    private int ticketNumber;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public TrainTicket2(String ticketName, int ticketNumber) {
        this.ticketName = ticketName;
        this.ticketNumber = ticketNumber;
    }

    // 售票
    public void saleTicket() {
        while (true) {
            lock.lock();
            try {
                condition.signal();
                if (ticketNumber > 0) {
                    System.out.println(Thread.currentThread().getName() + "正在卖第" + (ticketNumber--) + "张票");
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
    }
}

public class TicketTest2 {

    public static void main(String[] args) {
        TrainTicket2 ticket = new TrainTicket2("火车票", 50);
        new Thread(new Runnable() {
            @Override
            public void run() {
                ticket.saleTicket();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                ticket.saleTicket();
            }
        }).start();
    }
}
